package com.xyz.service.impl;

import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xyz.dao.mapper.RepairDaoMapper;
import com.xyz.dao.pojo.FaultTypeVo;
import com.xyz.dto.CountDto;
import com.xyz.dto.HomeLocalDateDto;
import com.xyz.dto.enums.EnumPatrolState;
import com.xyz.dto.enums.EnumRepState;
import com.xyz.entity.mapper.*;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.ExternalPostService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional(rollbackFor = Exception.class)
public class ExternalPostServiceImpl implements ExternalPostService {

    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Autowired
    private RepairMaintenanceMapper repairMaintenanceMapper;

    @Autowired
    private UpkeepWorkOrderMapper upkeepWorkOrderMapper;

    @Autowired
    private UpkeepMaintenanceMapper upkeepMaintenanceMapper;

    @Autowired
    private PatrolWorkOrderMapper patrolWorkOrderMapper;

    @Autowired
    private EquipmentTreeMapper equipmentTreeMapper;

    @Autowired
    private CommonService commonService;

    @Autowired
    private RepairDaoMapper repairDao;

    @Autowired
    private PlanInfoMapper planInfoMapper;


    @Override
    public DataResult selectEquipment(int pageNum, int pageSize) throws Exception {
        Map<Integer, String> typeMap = commonService.getDictMap("TYPE_EM_TYPE");
        Map<Long, EquipmentTree> treeMap = CollStreamUtil.toIdentityMap(equipmentTreeMapper.selectByExample(null), EquipmentTree::getId);

        EquipmentInfoExample eiExample = new EquipmentInfoExample();
        EquipmentInfoExample.Criteria eiCriteria = eiExample.createCriteria();
        eiCriteria.andIsDeleteEqualTo(0);
        eiExample.setOrderByClause("create_time desc");
        Page<EquipmentInfo> page = PageHelper.startPage(pageNum, pageSize);
        List<EquipmentInfo> eiList = equipmentInfoMapper.selectByExample(eiExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (EquipmentInfo ei : eiList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", ei.getId());
            map.put("emName", ei.getEmName());
            map.put("emCode", ei.getEmCode());
            map.put("archiveCode", ei.getArchiveCode());
            map.put("assetCode", ei.getAssetCode());
            map.put("dataCode", ei.getDataCode());
            map.put("factoryCode", ei.getFactoryCode());
            map.put("emGrade", ei.getEmGrade());
            map.put("emSpecification", ei.getEmSpecification());
            map.put("mainParameter", ei.getMainParameter());
            map.put("emLocation", ei.getEmLocation());
            map.put("emTreeId", ei.getEmTree());
            map.put("emType", typeMap.getOrDefault(ei.getEmType(), ""));
            map.put("manufacturer", ei.getManufacturer());
            map.put("isProvide", ei.getIsProvide());
            map.put("isSpecial", ei.getIsSpecial());

            map.put("emState", ei.getEmState());
            map.put("unit", ei.getUnit());
            map.put("operationTime", DateUtil.formatDate(ei.getOperationTime()));
            map.put("purchaseTime", DateUtil.formatDate(ei.getPurchaseTime()));
            map.put("factoryTime", DateUtil.formatDate(ei.getFactoryTime()));

            map.put("specialNextTime", (ei.getSpecialNextTime() == null || ei.getIsSpecial() == 0) ? "" : DateUtil.formatDate(ei.getSpecialNextTime()));
            map.put("isScrap", ei.getIsScrap());


            String emArea = "";
            String emSystem = "";
            String emSubsystem = "";
            String emGroup = "";

            EquipmentTree tree = treeMap.get(ei.getEmTree());
            if (tree != null) {
                long systemTreeId = 0L;
                if (tree.getType() == 3) {
                    emGroup = tree.getName();
                    EquipmentTree subsystem = treeMap.get(tree.getBaseId());
                    if (subsystem != null) {
                        emSubsystem = subsystem.getName();
                        systemTreeId = subsystem.getBaseId();
                    }
                } else {
                    emSubsystem = tree.getName();
                    systemTreeId = tree.getBaseId();
                }

                EquipmentTree system = treeMap.get(systemTreeId);
                if (system != null) {
                    emSystem = system.getName();
                    EquipmentTree area = treeMap.get(system.getBaseId());
                    if (area != null) {
                        emArea = area.getName();
                    }
                }


            }
            map.put("emArea", emArea);
            map.put("emSystem", emSystem);
            map.put("emSubsystem", emSubsystem);
            map.put("emGroup", emGroup);
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult selectLinearData(String startTime, String endTime, String type) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HomeLocalDateDto getDto = getHomeDto(startTime, endTime);
        //wx(维修趋势曲线图)；wxgz(故障曲线图)
        if ("wx".equals(type)) {
            resultMap = getWxData(getDto);
        } else if ("xj".equals(type)) {
            resultMap = getXjData(getDto);
        } else if ("wxgz".equals(type)) {
            resultMap = getWxgzData(getDto);
        }
        resultMap.put("type", type);
        return DataResult.build9100(resultMap);
    }

    /*
     * 分类汇总
     * */
    @Override
    public DataResult selectSubtotal(String startTime, String endTime, String type, String pageSize) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        HomeLocalDateDto getDto = getHomeDto(startTime, endTime);
        Integer size = null;
        if (StrUtil.isNotBlank(pageSize)) {
            size = Integer.parseInt(pageSize);
        }
        //sbgzbt（设备故障饼图）；wxph（维修排行）；pjph（人员评价排行）；gdph（人员处理工单数排行）；gsph（人员处理工单工时排行）；bjsy（备件使用排行）
        if ("sbgzbt".equals(type)) {
            resultMap = getSbgzbtData(getDto);
        } else if ("wxph".equals(type)) {
            resultMap = getWxphData(getDto, size);
        } else if ("pjph".equals(type)) {
            resultMap = getPjphData(getDto, size);
        } else if ("gdph".equals(type)) {
            resultMap = getGdphData(getDto, size);
        } else if ("gsph".equals(type)) {
            resultMap = getGsphData(getDto, size);
        } else if ("bjsy".equals(type)) {
            resultMap = getBjsyData(getDto, size);
        }
        resultMap.put("type", type);
        return DataResult.build9100(resultMap);
    }

    /*
     * 查询工单
     * */
    @Override
    public DataResult selectRo(String startTime, String endTime, String type) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        int total = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //wx(维修工单)，wb(维保工单)，xj(巡检工单)
        if ("wx".equals(type)) {
            RepairWorkOrderExample tExample = new RepairWorkOrderExample();
            RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();
            if (StrUtil.isNotEmpty(startTime)) {
                repCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(startTime + " 00:00:00"));
            }
            if (StrUtil.isNotEmpty(endTime)) {
                repCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(endTime + " 23:59:59"));
            }
            tExample.setOrderByClause("create_time desc");
            List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);
            for (RepairWorkOrder rw : repairList) {
                Map<String, Object> map = new HashMap<>();
                map.put("roId", rw.getRepId());
                map.put("roCode", rw.getWorkOrderCode());
                map.put("emId", rw.getEmId());
                map.put("emName", rw.getEmName());
                map.put("emCode", rw.getEmCode());
                map.put("emLocation", rw.getEmLocation());
                map.put("state", rw.getRepState());
                map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                dataList.add(map);
            }
            total = repairList.size();
        } else if ("wb".equals(type)) {
            UpkeepWorkOrderExample keepExample = new UpkeepWorkOrderExample();
            UpkeepWorkOrderExample.Criteria keepCriteria = keepExample.createCriteria();
            if (StrUtil.isNotEmpty(startTime)) {
                keepCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(startTime + " 00:00:00"));
            }
            if (StrUtil.isNotEmpty(endTime)) {
                keepCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(endTime + " 23:59:59"));
            }
            keepExample.setOrderByClause("create_time desc");
            List<UpkeepWorkOrder> keepWorkList = upkeepWorkOrderMapper.selectByExample(keepExample);
            for (UpkeepWorkOrder rw : keepWorkList) {
                Map<String, Object> map = new HashMap<>();
                map.put("roId", rw.getUpkeepId());
                map.put("roCode", rw.getWorkOrderCode());
                map.put("emId", rw.getEmId());
                map.put("emName", rw.getEmName());
                map.put("emCode", rw.getEmCode());
                map.put("emLocation", rw.getEmLocation());
                map.put("state", rw.getUpkeepState());
                map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                dataList.add(map);
            }
            total = keepWorkList.size();
        } else if ("xj".equals(type)) {
            PatrolWorkOrderExample pwoExample = new PatrolWorkOrderExample();
            PatrolWorkOrderExample.Criteria pwoCriteria = pwoExample.createCriteria();
            if (StrUtil.isNotEmpty(startTime)) {
                pwoCriteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(startTime + " 00:00:00"));
            }
            if (StrUtil.isNotEmpty(endTime)) {
                pwoCriteria.andCreateTimeLessThanOrEqualTo(sdf.parse(endTime + " 23:59:59"));
            }
            pwoExample.setOrderByClause("create_time desc");
            List<PatrolWorkOrder> pwoList = patrolWorkOrderMapper.selectByExample(pwoExample);

            EquipmentTreeExample example = new EquipmentTreeExample();
            EquipmentTreeExample.Criteria criteria = example.createCriteria();
            criteria.andTypeNotEqualTo(3);
            List<EquipmentTree> equipmentTrees = equipmentTreeMapper.selectByExample(example);
            Map<Long, EquipmentTree> treeMap = new HashMap<>();
            equipmentTrees.forEach(t -> treeMap.put(t.getId(), t));
            for (PatrolWorkOrder rw : pwoList) {
                Map<String, Object> map = new HashMap<>();
                map.put("roId", rw.getId());
                map.put("roCode", rw.getCode());
                map.put("emId", null);
                map.put("emName", "");
                map.put("emCode", "");
                map.put("emLocation", getLocat(treeMap, rw.getTreeId()));
                map.put("state", rw.getState());
                map.put("createTime", DateUtil.format(rw.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                dataList.add(map);
            }
            total = pwoList.size();
        }
        resultMap.put("type", type);
        resultMap.put("total", total);
        resultMap.put("dataList", dataList);
        return DataResult.build9100(resultMap);
    }

    /*
     * 获取维修时间巡检时间维保时间
     * */
    @Override
    public DataResult selectTimeByEmCode(String emCode) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        EquipmentInfoExample equipmentInfoExample = new EquipmentInfoExample();
        equipmentInfoExample.createCriteria().andEmCodeEqualTo(emCode);
        equipmentInfoExample.setOrderByClause("create_time desc");
        List<EquipmentInfo> equipmentInfoList = equipmentInfoMapper.selectByExample(equipmentInfoExample);
        //设备上次维修时间
        String lastDeviceRepairTime = null;
        //设备上次巡检时间
        String lastPatrolinspectionTime = null;
        //设备下次巡检时间
        String nextPatrolinspectionTime = null;
        //设备上次维保时间
        String lastMaintenanceTime = null;
        //设备下次维保时间
        String nextMaintenanceTime = null;
        if(CollUtil.isNotEmpty(equipmentInfoList)){
            EquipmentInfo equipmentInfo = equipmentInfoList.get(0);
            //查询设备上次维修时间
            RepairWorkOrderExample tExample = new RepairWorkOrderExample();
            RepairWorkOrderExample.Criteria repCriteria = tExample.createCriteria();
            repCriteria.andEmIdEqualTo(equipmentInfo.getId());
            repCriteria.andRepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            tExample.setOrderByClause("rep_end_time desc limit 1");
            List<RepairWorkOrder> repairList = repairWorkOrderMapper.selectByExample(tExample);
            if (CollUtil.isNotEmpty(repairList)) {
                RepairMaintenanceExample repMainExample = new RepairMaintenanceExample();
                RepairMaintenanceExample.Criteria repMainCriteria = repMainExample.createCriteria();
                repMainCriteria.andRepIdEqualTo(repairList.get(0).getRepId());
                repMainCriteria.andMtcStateEqualTo(repairList.get(0).getRepState());
                repMainExample.setOrderByClause("create_time desc limit 1");
                List<RepairMaintenance> repairMaintenanceList = repairMaintenanceMapper.selectByExample(repMainExample);
                if(CollUtil.isNotEmpty(repairMaintenanceList) && repairMaintenanceList.get(0).getMtcStartTime() != null){
                    lastDeviceRepairTime = DateUtil.format(repairMaintenanceList.get(0).getMtcStartTime(), "yyyy-MM-dd HH:mm:ss");
                }
            }
            //查询设备上次巡检时间
            PatrolWorkOrderExample pwoExample = new PatrolWorkOrderExample();
            PatrolWorkOrderExample.Criteria pwoCriteria = pwoExample.createCriteria();
            pwoCriteria.andTreeIdEqualTo(equipmentInfo.getSubTreeId());
            pwoCriteria.andStateEqualTo(EnumPatrolState.MAINTENANCE_YES.getState());
            pwoExample.setOrderByClause("ro_start_time desc limit 1");
            List<PatrolWorkOrder> pwoList = patrolWorkOrderMapper.selectByExample(pwoExample);
            if(CollUtil.isNotEmpty(pwoList) && pwoList.get(0).getRoStartTime() != null){
                lastPatrolinspectionTime = DateUtil.format(pwoList.get(0).getRoStartTime(), "yyyy-MM-dd HH:mm:ss");
            }
            //查询设备下次巡检时间
            Date currentDate = new Date();
            PlanInfoExample piExample = new PlanInfoExample();
            PlanInfoExample.Criteria piCriteria = piExample.createCriteria();
            //PlanType =2 巡检计划
            piCriteria.andTreeIdEqualTo(equipmentInfo.getSubTreeId());
            piCriteria.andPlanTypeEqualTo(2);
            piCriteria.andIsDeleteEqualTo(1);
            piCriteria.andMinuteTimeGreaterThan(currentDate);
            piExample.setOrderByClause("minute_time asc limit 1");
            List<PlanInfo> piList = planInfoMapper.selectByExample(piExample);
            if(CollUtil.isNotEmpty(piList) && piList.get(0).getMinuteTime() != null){
                nextPatrolinspectionTime = DateUtil.format(piList.get(0).getMinuteTime(), "yyyy-MM-dd HH:mm:ss");
            }
            //查询设备上次维保时间
            UpkeepWorkOrderExample keepExample = new UpkeepWorkOrderExample();
            UpkeepWorkOrderExample.Criteria keepCriteria = keepExample.createCriteria();
            keepCriteria.andEmIdEqualTo(equipmentInfo.getId());
            keepCriteria.andUpkeepStateEqualTo(EnumRepState.MAINTENANCE_YES.getRepState());
            keepExample.setOrderByClause("upkeep_start_time desc limit 1");
            List<UpkeepWorkOrder> keepWorkList = upkeepWorkOrderMapper.selectByExample(keepExample);
            if(CollUtil.isNotEmpty(keepWorkList)){
                UpkeepMaintenanceExample keepMainExample = new UpkeepMaintenanceExample();
                UpkeepMaintenanceExample.Criteria keepMainCriteria = keepMainExample.createCriteria();
                keepMainCriteria.andUpkeepIdEqualTo(keepWorkList.get(0).getUpkeepId());
                keepMainCriteria.andMtcStateEqualTo(keepWorkList.get(0).getUpkeepState());
                keepMainExample.setOrderByClause("create_time desc limit 1");
                List<UpkeepMaintenance> upkeepMaintenanceList = upkeepMaintenanceMapper.selectByExample(keepMainExample);
                if(CollUtil.isNotEmpty(upkeepMaintenanceList) && upkeepMaintenanceList.get(0).getMtcStartTime() != null){
                    lastMaintenanceTime = DateUtil.format(upkeepMaintenanceList.get(0).getMtcStartTime(), "yyyy-MM-dd HH:mm:ss");
                }
            }
            //查询设备下次维保时间
            PlanInfoExample pi2Example = new PlanInfoExample();
            PlanInfoExample.Criteria pi2Criteria = pi2Example.createCriteria();
            //PlanType =1 维保计划
            pi2Criteria.andEmIdEqualTo(equipmentInfo.getId());
            pi2Criteria.andPlanTypeEqualTo(1);
            pi2Criteria.andIsDeleteEqualTo(1);
            pi2Criteria.andChangeTimeGreaterThan(currentDate);
            pi2Example.setOrderByClause("change_time asc limit 1");
            List<PlanInfo> pi2List = planInfoMapper.selectByExample(pi2Example);
            if(CollUtil.isNotEmpty(pi2List) && pi2List.get(0).getChangeTime() != null){
                nextMaintenanceTime = DateUtil.format(pi2List.get(0).getChangeTime(), "yyyy-MM-dd HH:mm:ss");
            }
        }
        //设备上次维修时间
        resultMap.put("LastDeviceRepairTime", lastDeviceRepairTime);
        //设备上次巡检时间
        resultMap.put("LastPatrolinspectionTime", lastPatrolinspectionTime);
        //设备下次巡检时间
        resultMap.put("NextPatrolinspectionTime", nextPatrolinspectionTime);
        //设备上次维保时间
        resultMap.put("LastMaintenanceTime", lastMaintenanceTime);
        //设备下次维保时间
        resultMap.put("NextMaintenanceTime", nextMaintenanceTime);
        return DataResult.build9100(resultMap);
    }

    /*
     * 备件使用排行
     * */
    private Map<String, Object> getBjsyData(HomeLocalDateDto getDto, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> partRankingList = repairDao.queryPartRankingList(getDto.getStartTime(), getDto.getEndTime(), pageSize);
        List<Map<String, Object>> dataList = getDataMapList(partRankingList, "name", "count");
        resultMap.put("dataList", dataList);
        resultMap.put("total", null);
        return resultMap;
    }


    /*
     * 人员处理工单工时排行
     * */
    private Map<String, Object> getGsphData(HomeLocalDateDto getDto, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> hoursPersonRankingList = repairDao.queryHoursPersonRanking(getDto.getStartTime(), getDto.getEndTime(), pageSize);
        List<Map<String, Object>> dataList = getDataMapList(hoursPersonRankingList, "employeeName", "hourSum");
        resultMap.put("dataList", dataList);
        resultMap.put("total", null);
        return resultMap;
    }

    /*
     * 人员处理工单数排行
     * */
    private Map<String, Object> getGdphData(HomeLocalDateDto getDto, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> roPersonRankingList = repairDao.queryRoPersonRanking(getDto.getStartTime(), getDto.getEndTime(), pageSize);
        List<Map<String, Object>> dataList = getDataMapList(roPersonRankingList, "employeeName", "roCount");
        resultMap.put("dataList", dataList);
        resultMap.put("total", null);
        return resultMap;
    }

    /*
     * 人员评价排行
     * */
    private Map<String, Object> getPjphData(HomeLocalDateDto getDto, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> scoreList = repairDao.queryScorePersonList(getDto.getStartTime(), getDto.getEndTime(), pageSize);
        List<Map<String, Object>> dataList = getDataMapList(scoreList, "employeeName", "acceptScore");
        resultMap.put("dataList", dataList);
        resultMap.put("total", null);
        return resultMap;
    }

    /*
     * 维修排行
     * */
    private Map<String, Object> getWxphData(HomeLocalDateDto getDto, Integer pageSize) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> roEmRankingList = repairDao.queryRoEmRankingList(getDto.getStartTime(), getDto.getEndTime(), pageSize);
        List<Map<String, Object>> dataList = getDataMapList(roEmRankingList, "emName", "roCount");
        resultMap.put("dataList", dataList);
        resultMap.put("total", null);
        return resultMap;
    }

    //转成统一反正
    private List<Map<String, Object>> getDataMapList(List<Map<String, Object>> list, String name, String count) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Map<String, Object> rowMap = new HashMap<>();
            rowMap.put("count", map.get(count));
            rowMap.put("name", MapUtil.getStr(map, name));
            resultList.add(rowMap);
        }
        return resultList;
    }

    /*
     * 设备故障饼图
     * */
    private Map<String, Object> getSbgzbtData(HomeLocalDateDto getDto) {
        Map<String, Object> resultMap = new HashMap<>();
        //查询设备故障类型数
        List<FaultTypeVo> faultTypeVoList = repairDao.queryFaultPieList(getDto.getStartTime(), getDto.getEndTime());
        List<SystemDictData> sddList = commonService.getSysDateListByCode("TYPE_REP_MAINTENANCE");
        List<Map<String, Object>> FaultPieList = new ArrayList<>();
        long total = 0L;
        for (SystemDictData dictData : sddList) {
            Map<String, Object> rowMap = new HashMap<>();
            //故障名称
            rowMap.put("name", dictData.getDictName());
            int count = 0;
            for (FaultTypeVo vo : faultTypeVoList) {
                if (dictData.getDictValue().equals(vo.getMtcFaultType())) {
                    count = vo.getCount();
                    total += count;
                    break;
                }
            }
            //数量
            rowMap.put("count", count);
            FaultPieList.add(rowMap);
        }

        resultMap.put("dataList", FaultPieList);
        resultMap.put("total", total);
        return resultMap;
    }

    private Map<String, Object> getXjData(HomeLocalDateDto dateDto) {
        PatrolWorkOrderExample pwoExample = new PatrolWorkOrderExample();
        PatrolWorkOrderExample.Criteria pwoCriteria = pwoExample.createCriteria();
        pwoCriteria.andCreateTimeBetween(dateDto.getStartTime(), dateDto.getEndTime());
        List<PatrolWorkOrder> pwoList = patrolWorkOrderMapper.selectByExample(pwoExample);

        Map<String, List<Integer>> pwoMap = new HashMap<>();
        for (PatrolWorkOrder pwo : pwoList) {
            String key = DateUtil.formatDate(pwo.getCreateTime());
            List<Integer> pwoMapList;
            if (pwoMap.containsKey(key)) {
                pwoMapList = pwoMap.get(key);
            } else {
                pwoMapList = CollUtil.newArrayList(0, 0);
            }
            pwoMapList.set(0, pwoMapList.get(0) + 1);
            if (pwo.getIsException() == 1) {
                pwoMapList.set(1, pwoMapList.get(1) + 1);
            }
            pwoMap.put(key, pwoMapList);
        }

        List<DateTime> dateList = DateUtil.rangeToList(dateDto.getStartTime(), dateDto.getEndTime(), DateField.DAY_OF_YEAR);

        List<String> chartNameList = new ArrayList<>();
        Map<String, Object> allMap = new HashMap<>();
        Map<String, Object> exceptionMap = new HashMap<>();

        List<Integer> allDataList = new ArrayList<>();
        List<Integer> exceptionDataList = new ArrayList<>();
        for (DateTime day : dateList) {
            chartNameList.add(DateUtil.format(day, "YYYY-MM-dd"));
            String key = DateUtil.formatDate(day);
            if (pwoMap.containsKey(key)) {
                List<Integer> pwoMapList = pwoMap.get(key);
                allDataList.add(pwoMapList.get(0));
                exceptionDataList.add(pwoMapList.get(1));
            } else {
                allDataList.add(0);
                exceptionDataList.add(0);
            }
        }

        List<Map<String, Object>> chartRowsList = new ArrayList<>();
        allMap.put("name", "巡检总单数");
        allMap.put("dataList", allDataList);
        chartRowsList.add(allMap);

        exceptionMap.put("name", "巡检异常单数");
        exceptionMap.put("dataList", exceptionDataList);
        chartRowsList.add(exceptionMap);

        Map<String, Object> map = new HashMap<>();
        map.put("dateNameList", chartNameList);
        map.put("chartRows", chartRowsList);
        return map;
    }

    private Map<String, Object> getWxData(HomeLocalDateDto dateDto) {
        RepairWorkOrderExample rwoExample = new RepairWorkOrderExample();
        RepairWorkOrderExample.Criteria rwoCriteria = rwoExample.createCriteria();
        rwoCriteria.andCreateTimeBetween(dateDto.getStartTime(), dateDto.getEndTime());
        List<RepairWorkOrder> rwoList = repairWorkOrderMapper.selectByExample(rwoExample);

        Map<String, List<Integer>> rwoMap = new HashMap<>();
        for (RepairWorkOrder rwo : rwoList) {
            String key = DateUtil.formatDate(rwo.getCreateTime());
            List<Integer> rwoMapList;
            if (rwoMap.containsKey(key)) {
                rwoMapList = rwoMap.get(key);
            } else {
                rwoMapList = CollUtil.newArrayList(0, 0, 0);
            }
            if (rwo.getSourceType() == null) {
                rwoMapList.set(0, rwoMapList.get(0) + 1);
            } else if (rwo.getSourceType() == 1) {
                rwoMapList.set(1, rwoMapList.get(1) + 1);
            } else if (rwo.getSourceType() == 2) {
                rwoMapList.set(2, rwoMapList.get(2) + 1);
            }
            rwoMap.put(key, rwoMapList);
        }

        List<DateTime> dateList = DateUtil.rangeToList(dateDto.getStartTime(), dateDto.getEndTime(), DateField.DAY_OF_YEAR);

        List<String> chartNameList = new ArrayList<>();
        Map<String, Object> repairMap = new HashMap<>();
        Map<String, Object> upkeepMap = new HashMap<>();
        Map<String, Object> patrolMap = new HashMap<>();

        List<Integer> repairDataList = new ArrayList<>();
        List<Integer> upkeepDataList = new ArrayList<>();
        List<Integer> patrolDataList = new ArrayList<>();
        for (DateTime day : dateList) {
            chartNameList.add(DateUtil.format(day, "YYYY-MM-dd"));
            String key = DateUtil.formatDate(day);
            if (rwoMap.containsKey(key)) {
                List<Integer> rwoMapList = rwoMap.get(key);
                repairDataList.add(rwoMapList.get(0));
                upkeepDataList.add(rwoMapList.get(1));
                patrolDataList.add(rwoMapList.get(2));
            } else {
                repairDataList.add(0);
                upkeepDataList.add(0);
                patrolDataList.add(0);
            }
        }

        List<Map<String, Object>> chartRowsList = new ArrayList<>();
        repairMap.put("name", "自主维修");
        repairMap.put("dataList", repairDataList);
        chartRowsList.add(repairMap);

        upkeepMap.put("name", "维保转维修");
        upkeepMap.put("dataList", upkeepDataList);
        chartRowsList.add(upkeepMap);

        patrolMap.put("name", "巡检转维修");
        patrolMap.put("dataList", patrolDataList);
        chartRowsList.add(patrolMap);

        Map<String, Object> map = new HashMap<>();
        map.put("dateNameList", chartNameList);
        map.put("chartRows", chartRowsList);

        return map;
    }

    //故障曲线图
    private Map<String, Object> getWxgzData(HomeLocalDateDto getDto) {
        Map<String, Object> resultMap = new HashMap<>();
        //开始日期
        LocalDate firstDay = getDto.getFirstDay();
        //结束日期
        LocalDate lastDay = getDto.getLastDay();
        //日期排序
        List<LocalDate> LocalDateList = getDateListBetweenDates(firstDay, lastDay);

        List<String> dateNameList = LocalDateList.stream().map(t -> t.getYear() + "-" + t.getMonth().getValue() + "-" + t.getDayOfMonth()).collect(Collectors.toList());
        //获取故障数据
        List<FaultTypeVo> voList = repairDao.queryFaultTypeByTime(firstDay, lastDay.atTime(LocalTime.MAX));
        List<Map<String, Object>> rows = new ArrayList<>();
        //故障类别List
        List<SystemDictData> sddList = commonService.getSysDateListByCode("TYPE_REP_MAINTENANCE");
        //数据分组
        Map<Integer, List<FaultTypeVo>> voListMap = new HashMap<>();
        if (CollUtil.isNotEmpty(voList)) {
            voListMap = voList.stream().collect(Collectors.groupingBy(FaultTypeVo::getMtcFaultType));
        }
        for (SystemDictData dictData : sddList) {
            List<FaultTypeVo> faultTypeVos = voListMap.get(dictData.getDictValue());
            Map<String, Object> rowMap = new HashMap<>();
            List<Integer> rowCountList = new ArrayList<>();
            //故障名称
            rowMap.put("name", dictData.getDictName());
            for (LocalDate localDate : LocalDateList) {
                boolean fag = true;
                if (CollUtil.isNotEmpty(faultTypeVos)) {
                    for (FaultTypeVo faultTypeVo : faultTypeVos) {
                        if (localDate.isEqual(faultTypeVo.getDay())) {
                            rowCountList.add(faultTypeVo.getCount());
                            fag = false;
                            faultTypeVos.remove(faultTypeVo);
                            break;
                        }
                    }
                }
                if (fag) {
                    rowCountList.add(0);
                }
            }
            rowMap.put("dataList", rowCountList);
            rows.add(rowMap);
        }
        resultMap.put("dateNameList", dateNameList);
        resultMap.put("chartRows", rows);
        return resultMap;
    }

    private HomeLocalDateDto getHomeDto(String startTime, String endTime) throws Exception {
        CountDto countDto = new CountDto();
        countDto.setType("4");
        countDto.setStartTime(startTime);
        countDto.setEndTime(endTime);
        return commonService.selectCountTime(countDto);
    }

    private String getLocat(Map<Long, EquipmentTree> treeMap, Long treeId) {
        String locat = "";
        EquipmentTree equipmentTree2 = treeMap.get(treeId);
        if (equipmentTree2 != null) {
            locat = equipmentTree2.getName();
            EquipmentTree equipmentTree1 = treeMap.get(equipmentTree2.getBaseId());
            if (equipmentTree1 != null) {
                locat = equipmentTree1.getName() + "-" + locat;
                EquipmentTree equipmentTree = treeMap.get(equipmentTree1.getBaseId());
                if (equipmentTree != null) {
                    locat = equipmentTree.getName() + "-" + locat;
                }
            }
        }
        return locat;
    }

    private List<LocalDate> getDateListBetweenDates(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!startDate.isAfter(endDate)) {
            dateList.add(startDate);
            startDate = startDate.plusDays(1);
        }
        return dateList;
    }

}
